public class CanPartition {
    // leetcode 分隔等和子集
    // https://leetcode.cn/problems/partition-equal-subset-sum/description/?envType=study-plan-v2&envId=top-100-liked
    public boolean canPartition(int[] nums) {
        // 01背包问题
        // dp[i][j]表示从前i个元素中选取元素，背包中的最大容量
        // dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-nums[i]] + nums[i])
        int sum = 0;
        for (int num : nums) sum += num;
        if (sum % 2 != 0) return false;
        int n = nums.length;
        int[][] dp = new int[n+1][sum/2+1];
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= sum/2; j++) {
                dp[i][j] = dp[i-1][j];
                if (j >= nums[i-1]) {
                    dp[i][j] = Math.max(dp[i][j], dp[i-1][j-nums[i-1]] + nums[i-1]);
                }
            }
        }
        return dp[n][sum/2] == sum/2;
    }

    public boolean canPartition1(int[] nums) {
        // 01背包问题
        // dp[i][j]表示从前i个元素中选取元素，是否能装满背包容量为j的背包
        // dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-nums[i]] + nums[i])
        int sum = 0;
        for (int num : nums) sum += num;
        if (sum % 2 != 0) return false;
        int n = nums.length;
        sum /= 2;
        boolean[][] dp = new boolean[n+1][sum+1];
        dp[0][0] = true;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= sum; j++) {
                dp[i][j] = dp[i-1][j];
                if (j >= nums[i-1]) {
                    dp[i][j] = dp[i][j] || dp[i-1][j-nums[i-1]];
                }
            }
        }
        return dp[n][sum];
    }
}
